﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Input;
using System.Linq;
using System.Text;
using System.Windows;

namespace Com.CodePlex.SPC3.SPbAM.Controller {

	//http://code.google.com/p/wpf-mvvm-calculator/source/browse/trunk/Calculator/Commands/CommandReference.cs?spec=svn2&r=2   
	//http://joyfulwpf.blogspot.com/2009/05/mvvm-commandreference-and-keybinding.html
	public class CommandReference : Freezable, ICommand {

		public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));

		public ICommand Command {
			get { return (ICommand)GetValue(CommandProperty); }
			set { SetValue(CommandProperty, value); }
		}

		public bool CanExecute(object parameter) {
			if (Command != null)
				return Command.CanExecute(parameter);
			return false;
		}

		public void Execute(object parameter) {
			Command.Execute(parameter);
		}

		public event EventHandler CanExecuteChanged;

		private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
			CommandReference commandReference = d as CommandReference;
			ICommand oldCommand = e.OldValue as ICommand;
			ICommand newCommand = e.NewValue as ICommand;
			if (oldCommand != null) {
				oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
			}
			if (newCommand != null) {
				newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
			}
		}

		protected override Freezable CreateInstanceCore() {
			throw new NotImplementedException();
		}
	}
}
